package com.itheima.activiti.controller.business;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.activiti.auth.JwtContextUtils;
import com.itheima.activiti.common.R;
import com.itheima.activiti.dto.activiti.ProcessDataDTO;
import com.itheima.activiti.dto.activiti.ProcessInstanceDTO;
import com.itheima.activiti.dto.business.LeavesDTO;
import com.itheima.activiti.entity.business.Leaves;
import com.itheima.activiti.service.activiti.ProcessService;
import com.itheima.activiti.service.business.LeaveService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/leave")
@Api(tags = "请假")
public class LeaveController {

    @Autowired
    private LeaveService leaveService;
    @Autowired
    private ProcessService processService;

    /**
     * 新增
     */
    @PostMapping
    @ApiOperation(value = "新增")
    public R<Leaves> save(@RequestBody Leaves leaves) {
        log.info("leave:{}", leaves);
        leaveService.save(leaves);
        return R.success(leaves);
    }

    /**
     * 编辑
     */
    @PutMapping
    @ApiOperation(value = "修改")
    public R<Leaves> update(@RequestBody Leaves leaves) {
        log.info("leave:{}", leaves);
        leaveService.updateById(leaves);
        return R.success(leaves);
    }

    /**
     * 删除
     */
    @DeleteMapping
    @ApiOperation(value = "删除")
    public R delete(@RequestParam List<String> ids) {
        leaveService.removeByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 查询详情
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "查询")
    public R<Leaves> get(@PathVariable Long id) {
        Leaves leaves = leaveService.getById(id);
        if (leaves != null) {
            return R.success(leaves);
        } else {
            return R.error("没有找到该对象");
        }
    }

    /**
     * 自动分页查询
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页")
    public R<Page<LeavesDTO>> page(Leaves leaves,
                                   @RequestParam(required = false, defaultValue = "1") int page,
                                   @RequestParam(required = false, defaultValue = "10") int pageSize) {
        log.info("page:{}  pageSize:{}  leave:{}", page, pageSize, leaves);
        //分页构造器
        Page<Leaves> buildPage = new Page(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Leaves> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(leaves.getName()), Leaves::getName, leaves.getName());
        queryWrapper.eq(Leaves::getCreateUser, JwtContextUtils.getUser().getId());
        queryWrapper.eq(null != leaves.getType(), Leaves::getType, leaves.getType());
        queryWrapper.orderByDesc(Leaves::getCreateTime);
        //执行分页
        leaveService.page(buildPage, queryWrapper);
        Page<LeavesDTO> pages = new Page<>(page, pageSize, buildPage.getTotal());
        List<LeavesDTO> leavesDTOs = buildPage.getRecords().stream().map(item -> {
            LeavesDTO leavesDTO = new LeavesDTO();
            BeanUtil.copyProperties(item, leavesDTO);
            ProcessDataDTO processData = processService.processData(item.getId());
            BeanUtil.copyProperties(processData, leavesDTO);
            return leavesDTO;
        }).collect(Collectors.toList());
        pages.setRecords(leavesDTOs);
        //返回结果
        return R.success(pages);
    }

    /**
     * 全部查询
     */
    @GetMapping("/list")
    @ApiOperation(value = "列表")
    public R<List<Leaves>> list(Leaves leaves) {
        log.info("leave:{}", leaves);
        //条件构造器
        LambdaQueryWrapper<Leaves> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(leaves.getName()), Leaves::getName, leaves.getName());
        queryWrapper.eq(Leaves::getCreateUser, JwtContextUtils.getUser().getId());
        queryWrapper.eq(null != leaves.getType(), Leaves::getType, leaves.getType());

        return R.success(leaveService.list(queryWrapper));
    }

    @PostMapping("start")
    @ApiOperation(value = "申请")
    public R<ProcessInstanceDTO> start(@RequestBody Leaves leaves) {
        log.info("leave:{}", leaves);
        ProcessInstance instance = leaveService.start(leaves);
        ProcessInstanceDTO processInstanceDTO = new ProcessInstanceDTO();
        BeanUtil.copyProperties(instance, processInstanceDTO);
        return R.success(processInstanceDTO);
    }

    @PutMapping("commit")
    @ApiOperation(value = "提交")
    public R<ProcessInstanceDTO> commit(@RequestBody Leaves leaves) {
        log.info("leave:{}", leaves);
        ProcessInstance instance = leaveService.commit(leaves);
        ProcessInstanceDTO processInstanceDTO = new ProcessInstanceDTO();
        BeanUtil.copyProperties(instance, processInstanceDTO);
        return R.success(processInstanceDTO);
    }
}
